'''
Created on Mar 24, 2014

@author: kieubinh
'''
import sys
sys.path.append('libsvm-3.17/python/')

from svmutil import *
#linkFileTrain = "features_train_all_1.txt"
#linkFileTest = "features4_test.txt"
#linkFileOutput = "output4_train_all_1.txt"

#linkFileTrain = "features_train_unittest.txt"
#linkFileTest = "features_rite_val_test_1.txt"
#linkFileOutput = "output_rite_val_test_binhkt_train_unittest_SVR.txt"

linkFileTrain = "features_training_old.txt"
linkFileTest = "features_testing_old.txt"
linkFileOutput = "output_old.txt"

#max = 100000
#number_train = 65000

import os
directory_path = os.getcwd()

if __name__ == '__main__':  
    # get root path to ../javn/
    #dir_now = directory_path[:directory_path.find("javn")+5]
    dir_now=""
    name_file = dir_now + linkFileTrain  
    f_in = open(name_file,'r')
    count = 0
    for line in f_in:
        if len(line)>=5:
            count+=1
    
    f_in.close()

    #train = 90%
    #number_train = int(0.9*count)
    #print "The number of training instances: "+str(number_train)
    #print "The number of testing instances: "+str(count-number_train)
    import time
    
    start_time = time.time()
    y, x, id = svm_read_problem(name_file)
    
    
    #training c-SVC, radial basis function kernel
    m = svm_train(y, x, '-s 3 -t 2')
    #m = svm_train(y, x, '-s 0 -t 2')
    #m = svm_train(y,x, '-s 2 -t 2 -h 0')    
    print m


    print "The running time of training: "+str(time.time()-start_time)
    #train
    #print "training result......................................................."
    
    # --------------------------------------------- Testing
    
    name_file_test = dir_now + linkFileTest
    #import time
    
    start_time = time.time()
    y_test, x_test, y_id = svm_read_problem(name_file_test)  
    
    p_labels, p_acc, p_vals = svm_predict(y_test, x_test, m)
    out = open(linkFileOutput,'w')
#     print p_labels
#     for count in range(len(y_id)):
#         if p_labels[count]==1.0:
#             out.write(y_id[count]+" Y 1 \n")
#         else:
#             out.write(y_id[count]+" N 1 \n")
#     out.close()
    print p_labels
    prec = 0
    y_predict=[]
    for count in range(len(y_id)):
        if p_labels[count]>0.85:
            out.write(y_id[count]+" Y 1 \n")
            y_predict.append(1.0)
            if y_test[count]==1:
                prec+=1
        else:
            y_predict.append(0.0)
            out.write(y_id[count]+" N 1 \n")
    out.close()
    print prec
    print prec*1.0/len(y_test)
    print y_test
    print y_predict
    #test
    #print "testing result........................................................"
    #p_labels, p_acc, p_vals = svm_predict(y[number_train:], x[number_train:], m)
    #print p_labels
    #print p_acc
    #print evaluations(y[number_train:], p_labels)

